package com.atguigu.gmall.weball.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.list.GoodsFeignClient;
import com.atguigu.gmall.model.list.SearchParam;
import com.atguigu.gmall.model.list.SearchResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 检索功能控制器
 */
@Controller
public class SearchController {


    @Autowired
    GoodsFeignClient goodsFeignClient;
    /**
     * 分类：category3Id=61
     * 品牌：trademark=1:小米    id:name
     * 排序：order=2:asc      1（综合）: desc/asc    2（价格）:  desc/asc
     * 分页：pageNo=1
     * 属性：props=24:256G:机身内存  会传递很多平台属性条件
     * 关键字： keyword=手机     模糊全文检索符合手机的
     *
     * @RequestParam(value = "category3Id",required = false) Long category3Id,
     * @RequestParam(value = "trademark",required = false)String trademark,
     * @RequestParam(value = "order",required = false)String order,
     * @RequestParam(value = "pageNo",required = false)Long pageNo,
     * @RequestParam(value = "props",required = false)String props[],
     * @RequestParam(value = "keyword",required = false)String keyword
     * 把这些统一封装到一个JavaBean中
     * @param searchParam 检索 前端页面传递的所有参数；前端传递的参数自动封装到这个JavaBean
     * @return
     */
    @GetMapping("/list.html")
    public String search(SearchParam searchParam, Model model, HttpServletRequest request){


        //1、远程调用检索服务查出所有指定条件的商品

            SearchResponseVo responseVo = goodsFeignClient.searchGoods(searchParam);

            //给页面放入需要的数据
            //1、searchParam 代表所有以前前端传递来的检索条件，为了在新跳转的页面对以前的条件进行回显
            model.addAttribute("searchParam",searchParam); //web-all回填即可

            //2、trademarkParam 品牌的面包屑。自己组装；组装成： "品牌：小米"
            //trademark=1:小米
            if(!StringUtils.isEmpty(searchParam.getTrademark())){
                model.addAttribute("trademarkParam","品牌："+searchParam.getTrademark().split(":")[1]);
            }



            //3、propsParamList 平台属性的面包屑；集合；组装成： " ["运行内存：8G" , "机身内存：128G", "手机一级：安卓手机"]"
            //props=20:骁龙710:CPU品牌& props=21:3000mAh:电池信息
            if(searchParam.getProps()!=null && searchParam.getProps().length > 0){
                //制作属性的面包屑  attrName,attrValue,attrId
                //AttrJavaBean == Map<String,Object>
                List<Map<String, Object>> maps = Arrays.stream(searchParam.getProps())
                        .map((str) -> {
                            //props=21:3000mAh:电池信息
                            Map<String, Object> obj = new HashMap<>();
                            obj.put("attrId", str.split(":")[0]);
                            obj.put("attrValue", str.split(":")[1]);
                            obj.put("attrName", str.split(":")[2]);
                            return obj;
                        }).collect(Collectors.toList());
                //保存属性面包屑
                model.addAttribute("propsParamList",maps);
            }


            // #strings.replace(urlParam+'&order='+searchParam.order,'trademark='+searchParam.trademark,'')  ×  </a>
            // 后台，把当前所有的检索条件；拼接成url；（url里面有属性...）；urlParam，
            //4、urlParam url路径
            String url = makeUrl(searchParam);
            model.addAttribute("urlParam",url);
            //7、orderMap   排序信息
            Map<String,Object> orderMap = new HashMap<>();
            //type: 1 2
            //sort: asc desc
            String order = searchParam.getOrder(); //
            if(!StringUtils.isEmpty(order)){
                orderMap.put("type",order.split(":")[0]);
                orderMap.put("sort",order.split(":")[1]);
            }else {
                orderMap.put("type","1");
                orderMap.put("sort","desc");
            }
            model.addAttribute("orderMap",orderMap);



            //5、trademarkList  品牌列表； 检索页面头部展示的当前所有商品牵扯到的所有品牌
            model.addAttribute("trademarkList",responseVo.getTrademarkList());//集合

            //6、attrsList  属性集合； 检索页面头部展示的当前所有商品牵扯到的所有平台属性名和值
            model.addAttribute("attrsList",responseVo.getAttrsList());//集合



            //8、goodsList  商品集合
            model.addAttribute("goodsList",responseVo.getGoodsList());

            //9、pageNo   当前页
            model.addAttribute("pageNo",responseVo.getPageNo());

            //10、totalPages  总页面
            model.addAttribute("totalPages",responseVo.getTotalPages());
            return "list/index"; //调到检索列表页


    }

    /**
     * 根据前端上次的检索的条件，封装成一个url路径，交给前端
     * @param searchParam
     * @return
     */
    private String makeUrl(SearchParam searchParam) {

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("list.html?");

        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            stringBuffer.append("&keyword="+searchParam.getKeyword());
        }
        if(!StringUtils.isEmpty(searchParam.getTrademark())){
            stringBuffer.append("&trademark="+searchParam.getTrademark());
        }
        if(searchParam.getCategory3Id()!=null){
            stringBuffer.append("&category3Id="+searchParam.getCategory3Id());
        }
        if(searchParam.getProps()!=null && searchParam.getProps().length>0){
            for (String prop : searchParam.getProps()) {
                stringBuffer.append("&props="+prop); //1:8G:内存
            }
        }

        //不用拼pageNo
//        stringBuffer.append("&pageNo="+searchParam.getPageNo());
        //不用管
//        if(!StringUtils.isEmpty(searchParam.getOrder())){
//            stringBuffer.append("&order="+searchParam.getOrder());
//        }



        return stringBuffer.toString();
    }
}
